package com.bd.msdp.auth.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
@PropertySource("classpath:properties/db.properties")
public class MyBatisConfig {
	
	private static final Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);
	
	@Value("${db.type}")
	private String dbType;
	
	@Value("${jdbc.driver}")
	private String driverClassName;
	
	@Value("${jdbc.url}")
	private String url;
	
	@Value("${jdbc.username}")
	private String userName;
	
	@Value("${jdbc.password}")
	private String password;
	
	@Value("${validation.query}")
	private String validationQuery;
	
	@Bean
	public DataSource dataSource() {
		BasicDataSource  dataSource = new BasicDataSource();
	    dataSource.setDriverClassName(driverClassName);
	    dataSource.setUrl(url);
	    dataSource.setUsername(userName);
	    dataSource.setPassword(password);
	    dataSource.setValidationQuery(validationQuery);
	    return dataSource;
	}
	
	@Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource());
		
		logger.debug("dbType : " + dbType);
		
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactory.setMapperLocations(resolver.getResources("classpath:/mappers/" + dbType + "/*.xml"));
		sqlSessionFactory.setConfigLocation(new ClassPathResource("mappers/mybatis-config.xml"));
		
		return (SqlSessionFactory)sqlSessionFactory.getObject();
    }
	
	@Bean
    public SqlSessionTemplate sqlSession() throws Exception {
		SqlSessionTemplate sqlSessionTemplate =  new SqlSessionTemplate(sqlSessionFactory());
		return sqlSessionTemplate;
    }
    
	
	/*
	@Bean(name = "transactionManager")
	public PlatformTransactionManager transactionManager() {
	    return new DataSourceTransactionManager(dataSource());
	}
	*/
	
	/*
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }
    */
	
}
